﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace EzFrameWork
{
    //对Csv 进行读写操作
    class Csv
    {
        private List<string> v_List = new List<string>();//列

        private Dictionary<string, List<string>> valuePairs = new Dictionary<string, List<string>>();

        List<string> listTytle = new List<string>();//得到表头名字
        string key;
        public Csv()
        {
            
        }
        
        public Csv(string[] H)//第一行数据填满
        {
            for (int i = 0; i < H.Length; i++)
            {
                listTytle.Add(H[i]);
                Debug.Log(H[i]);
                valuePairs.Add(H[i], new List<string>());
            }
            valuePairs.Add("tytle", listTytle);
        }


        /// <summary>
        /// 向表中添加数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="data"></param>
        public void AddItem(string name, string data)
        {
            valuePairs[name].Add(data);
            v_List.Add(name);
        }

        public string ObjToCsv(string path = "Assets/StreamingAssets/CSV/", string name = "Defult_CSＶ")
        {
            string arr = "";
            for (int i = 0; i < valuePairs.Count - 1; i++)
            {
                arr += listTytle[i] + ",";
            }
            arr += "\n";
            for (int j = 0; j < valuePairs[v_List[0]].Count; j++)
            {
                for (int i = 0; i < valuePairs.Count - 1; i++)
                {
                    arr += (valuePairs[listTytle[i]])[j] + ",";
                }
                arr += "\n";
            }
            WriteTextToFile(path, name, arr);
            return arr;
        }

        private void WriteTextToFile(string path, string jsonFileName, string data)
        {
            string str = path + jsonFileName + ".csv";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);  //创建文件夹
            }
            if (File.Exists(str))
            {
                Debug.Log("有文件修改成功");
                File.WriteAllText(str, data);
            }
            else
            {
                FileStream fs = new FileStream(str, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter m_streamWriter = new StreamWriter(fs, Encoding.UTF8);   //UTF8格式写入
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                m_streamWriter.WriteLine(data);
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
        }
    }
}